package com.sskj.b70.v.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.TabLayout;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.MenuItem;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.sskj.b70.MyAppLication;
import com.sskj.b70.R;
import com.sskj.b70.common.App;
import com.sskj.b70.common.Constants;
import com.sskj.b70.common.MarketWebSocket;
import com.sskj.b70.common.rxbus2.RxBus;
import com.sskj.b70.common.rxbus2.Subscribe;
import com.sskj.b70.common.rxbus2.ThreadMode;
import com.sskj.b70.common.widget.ToolBarLayout;
import com.sskj.b70.m.StockCoinBean;
import com.sskj.b70.m.bean.Currency;
import com.sskj.b70.m.bean.Time;
import com.sskj.b70.m.bean.rxbus.MainTabChange;
import com.sskj.b70.m.bean.rxbus.StockCoinUpdate;
import com.sskj.b70.m.bean.rxbus.StockLevelUpdate;
import com.sskj.b70.p.activity.MarketPresenter;
import com.sskj.b70.utils.ClickUtil;
import com.sskj.b70.utils.NumberUtil;
import com.sskj.b70.v.base.BaseActivity;
import com.sskj.b70.v.base.BaseFragment;
import com.sskj.b70.v.fragment.ChartFragment;
import com.sskj.b70.v.fragment.SummaryFragment;
import com.sskj.b70.v.fragment.TradeFragment;
import com.sskj.b70.v.widget.NumberRunningTextView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

public class MarketNewActivity extends BaseActivity<MarketPresenter> {

    @BindView(R.id.priceNow)   // 当前价格
            NumberRunningTextView mPriceNow;
    @BindView(R.id.changeRate)   // 当前价格  右侧  百分比
            TextView mChangeRate;
    @BindView(R.id.highText)
    TextView mHighText;
    @BindView(R.id.highPrice)  // 高 价格
            TextView mHighPrice;
    @BindView(R.id.lowText)
    TextView mLowText;
    @BindView(R.id.lowPrice)  // 低  价格
            TextView mLowPrice;
    @BindView(R.id.marketFrame)
    FrameLayout mMarketFrame;
    @BindView(R.id.tablayout)
    TabLayout mTablayout;
    @BindView(R.id.market_viewpager)
    ViewPager mMarketViewpager;
    @BindView(R.id.marketTab)
    TabLayout marketTab;
    @BindView(R.id.toolBar)
    ToolBarLayout toolbar;
    private MarketWebSocket webSocket;
    @BindView(R.id.marketBuy)
    TextView mMarketBuy;
    @BindView(R.id.marketSale)
    TextView mMarketSale;
    @BindView(R.id.appbarlayout)
    AppBarLayout mAppbarlayout;
    @BindView(R.id.tvRMB)
    TextView tvRMB;
    private Time mTime;

    /**
     * 0 五大币 1 交易币
     */
    public Currency type;

    //要跳转的页面
    private int index = 2;
    private String code;
    private int currentIndex = 0;

    private ArrayList<BaseFragment> mFragments = new ArrayList();
    private String[] mTitles = new String[]{App.INSTANCE.getString(R.string.strMarketNewActivity0), App.INSTANCE.getString(R.string.strMarketNewActivity1)};
    private MyFragmentPagerAdapter mPagerAdapter;
    private ArrayList<ChartFragment> fragmentList = new ArrayList<>();
    String[] goodsType = {"minute", "minute", "minute5", "minute15", "minute30", "minute60", "day"};

    /**
     * @param context
     * @param code    type为0时传code，为1时传mark
     */
    public static void start(Activity context, String code) {
        Intent intent = new Intent(context, MarketNewActivity.class);
        intent.putExtra(Constants.CODE, code);
        context.startActivity(intent);
    }


    @Override
    protected int getLayoutResId() {
        return R.layout.activity_market_new;
    }

    @Override
    public MarketPresenter getPresenter() {
        return new MarketPresenter();
    }

    @Override
    protected void initView() {
        RxBus.getDefault().register(this);
        code = getIntent().getStringExtra("code");
        if (code.toUpperCase().endsWith("USDT") && !code.toUpperCase().contains("PSTR")) {
            mMarketBuy.setVisibility(View.VISIBLE);
            mMarketSale.setVisibility(View.VISIBLE);

        } else {
            mMarketBuy.setVisibility(View.VISIBLE);
            mMarketSale.setVisibility(View.GONE);
        }
        toolbar.setBackGroundColor(Color.parseColor("#031721"));
        toolbar.setTitleColor(Color.parseColor("#e4e4e4"));
        toolbar.setTitle(code.toUpperCase());
        toolbar.setTitleLeft();
        toolbar.setLeftButtonOnClickLinster((v) -> onBackPressed());
        toolbar.showUnderLine(false);
        mFragments.add(TradeFragment.newInstance(code));
        mFragments.add(SummaryFragment.newInstance(code));

        mPagerAdapter = new MyFragmentPagerAdapter(getSupportFragmentManager(), mTitles, mFragments);
        mMarketViewpager.setAdapter(mPagerAdapter);
        mTablayout.setupWithViewPager(mMarketViewpager);
        initTab();

    }

    @Override
    protected void initData() {
        mPresenter.getNewInfo(code);

        //币币交易
        ClickUtil.click(mMarketBuy, () -> {
//            RxBus.getDefault().post(new MainTabChange(1));
            if (MyAppLication.mainActvity != null) {
                MyAppLication.mainActvity.setCurrentTab(new MainTabChange(1));
            }
            RxBus.getDefault().post(new StockCoinUpdate(code));
            finish();
        });
        //合约交易
        ClickUtil.click(mMarketSale, () -> {
//            RxBus.getDefault().post(new MainTabChange(2));
            if (MyAppLication.mainActvity != null) {
                MyAppLication.mainActvity.setCurrentTab(new MainTabChange(2));
            }
            RxBus.getDefault().post(new StockLevelUpdate(code));
            finish();
        });
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updateUI(StockCoinBean.StockProductVOBean stock) {
        if (stock.getCode().equals(code)) {
            if (stock.getChange() > 0) {
                mChangeRate.setTextColor(getResources().getColor(R.color.market_down));
                mPriceNow.setTextColor(getResources().getColor(R.color.market_down));
            } else {
                mChangeRate.setTextColor(getResources().getColor(R.color.market_up));
                mPriceNow.setTextColor(getResources().getColor(R.color.market_up));
            }
            tvRMB.setText("≈" + stock.getCnyPrice() + "CNY");
            mChangeRate.setText(stock.getChangeRate());
            mHighPrice.setText(NumberUtil.keepNoZoreMax4(stock.getHigh()));
            mLowPrice.setText(NumberUtil.keepNoZoreMax4(stock.getLow()));
            mHighPrice.setTextColor(ContextCompat.getColor(MarketNewActivity.this, R.color.bull_light_white));
            mLowPrice.setTextColor(ContextCompat.getColor(MarketNewActivity.this, R.color.bull_light_white));
            mPriceNow.setText(stock.getPrice());
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void initTab() {
        fragmentList.add(null);
        fragmentList.add(null);
        fragmentList.add(null);
        fragmentList.add(null);
        fragmentList.add(null);
        fragmentList.add(null);
        fragmentList.add(null);
        marketTab.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                selectTab(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

        selectTab(0);
    }

    /**
     * k线切换
     *
     * @param index
     */
    private void selectTab(int index) {
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        ChartFragment minuteFragment = fragmentList.get(index);
        ChartFragment currentFragment = fragmentList.get(currentIndex);
        if (currentFragment != null) {
            ft.hide(currentFragment);
        }
        if (minuteFragment == null) {
            minuteFragment = ChartFragment.newInstance(code, goodsType[index], index != 0);
            fragmentList.set(index, minuteFragment);
            ft.add(R.id.marketFrame, minuteFragment);
        } else {
            ft.show(minuteFragment);
        }
        ft.commit();
        currentIndex = index;
    }


    public class MyFragmentPagerAdapter extends FragmentPagerAdapter {

        private String[] title;
        private List<BaseFragment> views;

        public MyFragmentPagerAdapter(FragmentManager fm, String[] title, List<BaseFragment> views) {
            super(fm);
            this.title = title;
            this.views = views;
        }

        public MyFragmentPagerAdapter(FragmentManager fm, List<BaseFragment> views) {
            super(fm);
            this.views = views;
        }

        @Override
        public BaseFragment getItem(int position) {
            return views.get(position);
        }

        @Override
        public int getCount() {
            return views.size();
        }

        @Override
        public int getItemPosition(Object object) {
            return PagerAdapter.POSITION_NONE;
        }

        //配置标题的方法
        @Override
        public CharSequence getPageTitle(int position) {
            return title == null ? "" : title[position];
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        RxBus.getDefault().unregister(this);
    }
}
